const fs = require('fs')

// promise 对象
const readfile = (filename) => {
	return new Promise((resolve, reject) => {
		fs.readFile(filename, {
			encoding: 'utf-8'
		}, (err, data) => {
			if (err) {
				reject(err)
				return
			}
			resolve(data)
		})
	})
}

readfile('./cc.md').then(data => {
	let info = data.match(/---[\r\n](.*[\r\n])+---/g)
	let all = info[0].match(/[\n](.*)[\r]/g)
	let d = {}
	all.forEach((item) => {
		let v = item.split(': ')
		d[v[0].replace(/\n/, '')] = v[1].replace(/\r/, '')
	})
	console.log(d)
}, err => console.error(err.message))


// example
// 接二连三
let p1 = new Promise(function(resolve, reject) {
	resolve(42);
});

p1.then(function(value) {
	console.log(value);
  return value += 4
}).then(function(value) {
	console.log("Finished" + value);
  return value += 9
}).then(function(value) {
	console.log('ok'+ value)
});


// 响应多个 Promise
// Promise.all() 方法
// 若传递给 Promise.all() 的任意 Promise 被拒绝了，
// 那么方法所返回的 Promise 就会立刻被拒绝，而不必等待其他的 Promise 结束
let p7 = new Promise(function(resolve, reject) {
    resolve(42);
});
let p8 = new Promise(function(resolve, reject) {
    resolve(43);
});
let p9 = new Promise(function(resolve, reject) {
    resolve(44);
});
let p4 = Promise.all([p7, p8, p9]);
p4.then(function(value) {
    console.log(Array.isArray(value));  // true
    console.log(value[0]);              // 42
    console.log(value[1]);              // 43
    console.log(value[2]);              // 44
});
